#include "cfont.h"


CFont * CFont::m_instance = NULL;

CFont::CFont()
{
    //在构造函数中初始化    液晶屏
    initLcd();
}

CFont::~CFont()
{
    destoryLcd();
}

void CFont::initLcd(const char *device)
{
    //申请空间
    m_lcd = (struct LcdDevice *)malloc(sizeof(struct LcdDevice));
    if(m_lcd == NULL)
    {
        return ;
    }

    //1打开设备
    m_lcd->fd = open(device, O_RDWR);
    if(m_lcd->fd < 0)
    {
        perror("open lcd fail");
        free(m_lcd);
        return ;
    }

    //映射
    m_lcd->mp = (unsigned int *)mmap(NULL,800*480*4,PROT_READ|PROT_WRITE,MAP_SHARED,m_lcd->fd,0);

}

void CFont::destoryLcd()
{
    ::close(m_lcd->fd);
    munmap(m_lcd->mp, 800*480*4);

    free(m_lcd);
}

void CFont::show( char *text, int pixelsize, int backgroundWidth, int backgroundHeight, int backgroundColor, int fontColor, int posXToLcd, int posYToLcd)
{
    //打开字体
    font *f = fontLoad((char*)"/usr/share/fonts/DroidSansFallback.ttf");

    //字体大小的设置
    fontSetSize(f,pixelsize);

    int bgc_red = backgroundColor>>16;
    int bgc_green = (backgroundColor>>8) & 0xff;
    int bgc_blue = backgroundColor  & 0xff;
    //创建一个画板（点阵图）
    bitmap *bm = createBitmapWithInit(backgroundWidth,backgroundHeight,4,getColor(0,bgc_red,bgc_green,bgc_blue)); //也可使用createBitmapWithInit函数，改变画板颜色
    //bitmap *bm = createBitmap(288, 100, 4);

    //将字体写到点阵图上
    int font_red = fontColor>>16;
    int font_green = (fontColor>>8) & 0xff;
    int font_blue = fontColor  & 0xff;
    fontPrint(f,bm,0,0,text,getColor(0,font_red,font_green,font_blue),0);

    //把字体框输出到LCD屏幕上
    show_font_to_lcd(m_lcd->mp,posXToLcd,posYToLcd,bm);

    //关闭字体，关闭画板
    fontUnload(f);
    destroyBitmap(bm);
}

void CFont::show(const char *text, int pixelsize, int backgroundWidth, int backgroundHeight, int backgroundColor, int fontColor, int posXToLcd, int posYToLcd)
{
    //打开字体
    font *f = fontLoad((char*)"/usr/share/fonts/DroidSansFallback.ttf");

    //字体大小的设置
    fontSetSize(f,pixelsize);

    int bgc_red = backgroundColor>>16;
    int bgc_green = (backgroundColor>>8) & 0xff;
    int bgc_blue = backgroundColor  & 0xff;
    //创建一个画板（点阵图）
    bitmap *bm = createBitmapWithInit(backgroundWidth,backgroundHeight,4,getColor(0,bgc_red,bgc_green,bgc_blue)); //也可使用createBitmapWithInit函数，改变画板颜色
    //bitmap *bm = createBitmap(288, 100, 4);

    //将字体写到点阵图上
    int font_red = fontColor>>16;
    int font_green = (fontColor>>8) & 0xff;
    int font_blue = fontColor  & 0xff;
    fontPrint(f,bm,0,0,(char*)text,getColor(0,font_red,font_green,font_blue),0);

    //把字体框输出到LCD屏幕上
    show_font_to_lcd(m_lcd->mp,posXToLcd,posYToLcd,bm);

    //关闭字体，关闭画板
    fontUnload(f);
    destroyBitmap(bm);
}

CFont *CFont::instance()
{
    if(m_instance == NULL)
    {
        m_instance = new CFont;
    }

    return m_instance;
}
